﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Event/ServiceCollectionExtensions 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       ServiceCollectionExtensions
* 创建时间：  2025/6/4 8:54:00
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using DotNetCore.CAP;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyModel;
using SSPivot.Common.Helpers;
using SSPivot.Event;
using SSPivot.Event.Config;
using SSPivot.Event.Demo;
using SSPivot.Event.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddEventBusSetup(this IServiceCollection services,IConfiguration configuration, Assembly[] assemblies) 
        {
            // 配置事件总线选项
            var config = configuration.GetSection("EventBus").Get<EventBusOptions>(); 
            if (config.EnableDistributedEvents)
            {
                if (config.UseRabbitMQ)
                {
                    // 配置CAP (RabbitMQ)
                    services.AddCap(options =>
                    {
                        options.UseSqlServer(config.ConnectionString);
                        options.UseRabbitMQ(conf =>
                        {
                            conf.HostName = config.RabbitMq.HostName;
                            conf.UserName = config.RabbitMq.UserName;
                            conf.Password = config.RabbitMq.Password;
                            conf.Port = config.RabbitMq.Port;
                            conf.VirtualHost = config.RabbitMq.VirtualHost;
                        });
                        // 启用仪表盘
                        options.UseDashboard(o => o.PathMatch = "/cap-dashboard");
                        options.DefaultGroupName = "eventbus.group";
                    });
                }
                else
                {
                    // 配置CAP (kafaka)
                    services.AddCap(options =>
                    {
                        options.UseSqlServer(config.ConnectionString);
                        options.UseKafka(config.KafakaServer);
                        options.UseDashboard(o => o.PathMatch = "/cap-dashboard");
                        options.DefaultGroupName = "eventbus.group";
                    });

                }

            }

            // 注册MediatR
            services.AddMediatR(config =>
                {
                    if(assemblies==null||assemblies.Length==0)
                    {
                        assemblies = DependencyContext.Default.CompileLibraries.Where(lib => lib.Name.StartsWith("SSPivot")).Select(e => Assembly.Load(e.Name)).ToArray();
                    }
                    config.RegisterServicesFromAssemblies(assemblies);
                });

            // 注册事件总线
            services.AddScoped<IEventPublisher, EventBus>();


            // 注册事件总线
            services.AddScoped<IEventPublisher, EventBus>();
            //// 添加数据库上下文
            //builder.Services.AddDbContext<AppDbContext>(options =>
            //    options.UseSqlite("Data Source=eventbus.db"));

            return services;
        }

        //test
        public static void UseEventBusSetup(this WebApplication app)
        {

            // / 初始化数据库
            //using (var scope = app.Services.CreateScope())
            //{
            //    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            //    db.Database.EnsureCreated();
            //}
            app.MapGet("/publish-local", async (IEventPublisher eventBus) =>
            {
                await eventBus.PublishLocalAsync(new LocalEvent("Local event triggered"));
                return "Local event published";
            });
            app.MapGet("/publish-distributed", async (IEventPublisher eventBus) =>
            {
                await eventBus.PublishDistributedAsync(
                    new DistributedEvent("Distributed event triggered", DateTime.UtcNow));
                return "Distributed event published";
            });

        }

  
    }
}
